package com.swxc.smartorder.ui.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView.HORIZONTAL
import android.util.Log
import android.view.View
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.reflect.TypeToken
import com.swxc.smartorder.R
import com.swxc.smartorder.adapter.AdapterImages
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.entity.BackEntity
import com.swxc.smartorder.entity.CommonDataList
import com.swxc.smartorder.entity.ImageEntity
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.utils.JsonUtil
import com.swxc.smartorder.utils.ToastUtil
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.compress.CompressHelper
import com.zhihu.matisse.compress.FileUtil
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_back_message.*
import java.io.File


/**
 * 回复工单
 */
class BackMessageActivity : BaseActivity(), View.OnClickListener {
    companion object {
        private const val REQUEST_CODE_CHOOSE = 23
        private const val MAX_IMAGE = 4
    }
    private var fileList: List<File>? = null

    private var mAdapter: AdapterImages? = null
    private var mImageList: MutableList<String>? = null
    private var mHelper: NetworkHelper? = null
    private var mOrderId: Long? = null
    private var mStaffId: Long? = null

    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.tv_cancel -> {
                finish()
            }
            R.id.tv_submit -> {
                submitInfo()
            }
            R.id.iv_choose_image -> {
                chooseImage()
            }
        }
    }

    /**
     * 提交信息
     */
    private fun submitInfo() {
        val strContent = edt_content.text.toString().trim()
        when {

        //回复内容为空的时候进行提示
            strContent.isEmpty() -> {
                val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_COMMON, "回复内容不能为空")
                toastUtil.show(2000)
            }

        //当存在图片  先上传图片获取图片的ID
            mImageList?.size!! > 0 -> {

                fileList?.let {
                    mHelper?.sendImage(GlobalAPI.sendImage, it, object : NetworkHelper.NetWorkHelperBack {
                        override fun requestSuccess(json: String) {
                            Log.e(BUG_TAG, json)
                            val type = object : TypeToken<CommonDataList<ImageEntity>>() {}.type
                            val fromJson = JsonUtil.fromJson<CommonDataList<ImageEntity>>(json, type)
                                    ?: return
                            when (fromJson.responseCode) {
                                1001 -> {
                                    val imageIds = StringBuilder()
                                    fromJson.data.forEach { imageIds.append(it.fileId).append(",") }
                                    imageIds.deleteCharAt(imageIds.lastIndex)
                                    handleOrder(strContent, imageIds.toString())

                                }
                            }
                        }

                        override fun requestFail() {

                            val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, "上传图片失败")
                            toastUtil.show(2000)
                        }
                    })
                }
            }
        //不存在图片直接上传内容
            else -> {
                handleOrder(strContent, "")


            }
        }
    }

    /**
     * 回复工单
     */
    fun handleOrder(strContent: String, imageIds: String) {
        mHelper?.handOrder(strContent, imageIds,
                mOrderId, mStaffId, "REPLY", object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                val fromJson = JsonUtil.fromJson<BackEntity>(json, BackEntity::class.java)
                        ?: return
                when (fromJson.responseCode) {
                    1001 -> {
                        val toastUtil = ToastUtil(mContext, true, ToastUtil.STATUS_SUCCESS, "回复成功")
                        toastUtil.show(2000)
                        finish()
                    }
                    else -> {
                        val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, fromJson.message)
                        toastUtil.show(2000)
                    }
                }
            }

            override fun requestFail() {
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_back_message)
        initBundleData()
        initViewAndEvent()
    }

    private fun initBundleData() {

        mOrderId = intent.extras.getLong("orderID")
        mStaffId = intent.extras.getLong("STAFF_ID")
    }

    /**
     * 初始化视图
     */
    private fun initViewAndEvent() {
        tv_cancel.setOnClickListener(this)
        tv_submit.setOnClickListener(this)
        iv_choose_image.setOnClickListener(this)
        fileList = ArrayList()
        mImageList = ArrayList()
        mHelper = NetworkHelper(mContext, supportFragmentManager)
        mAdapter = AdapterImages(mImageList)
        val linearLayoutManager = LinearLayoutManager(mContext)
        linearLayoutManager.orientation = HORIZONTAL
        rv_images.layoutManager = linearLayoutManager
        rv_images.adapter = mAdapter
        mAdapter?.onItemChildClickListener = BaseQuickAdapter.OnItemChildClickListener { _, _, position ->
            mAdapter?.remove(position)
            iv_choose_image.visibility = View.VISIBLE
        }
    }

    /**
     * 选择图片
     */
    private fun chooseImage() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(object : io.reactivex.Observer<Boolean> {
                    override fun onNext(aBoolean: Boolean) = if (aBoolean) {
                        Matisse.from(this@BackMessageActivity)
                                .choose(MimeType.ofImage(), false)
                                .countable(true)
                                .captureStrategy(CaptureStrategy(true, "com.swxc.smartorder.fileprovider"))
                                .maxSelectable(MAX_IMAGE)
                                .gridExpectedSize(resources.getDimensionPixelSize(R.dimen.grid_expected_size))
                                .capture(true)
                                .theme(R.style.matisse)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                                .thumbnailScale(0.85f)
                                .imageEngine(GlideEngine())
                                .forResult(REQUEST_CODE_CHOOSE)
                    } else {
                        Toast.makeText(this@BackMessageActivity, R.string.permission_request_denied, Toast.LENGTH_LONG)
                                .show()
                    }

                    override fun onComplete() {
                    }

                    override fun onError(e: Throwable) {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }
                })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {

            val obtainPathResult = Matisse.obtainPathResult(data)
            fileList = obtainPathResult.map {
                CompressHelper.getDefault(mContext).compressToFile(FileUtil.getFileByPath(it))
            }
            obtainPathResult.forEach { mImageList?.add(it) }
            when (mImageList?.size) {
                0 -> {
                    iv_choose_image.visibility = View.VISIBLE
                    rv_images.visibility = View.GONE
                }
                4 -> {
                    iv_choose_image.visibility = View.GONE
                    rv_images.visibility = View.VISIBLE
                }
                else -> {
                    iv_choose_image.visibility = View.VISIBLE
                }
            }
            mAdapter?.notifyDataSetChanged()
            mImageList?.forEach { Log.e(BUG_TAG, it) }
        }
    }

}
